﻿
#if WINDOWS
using Microsoft.UI;
using Microsoft.UI.Windowing;
using AppWindow = Microsoft.UI.Windowing.AppWindow;
#endif

using SharpHook;
using System.Diagnostics;
using ymk_camera_surveillance.Views;
using CommunityToolkit.Mvvm.Messaging;
using ymk_camera_surveillance.Views.CameraViews;
using ymk_camera_surveillance.Decode;

namespace ymk_camera_surveillance
{
    public partial class App : Application
    {
        static public InitFFmpeg initFFmpeg = null;
        static public TaskPoolGlobalHook KB_HOOK = null;
        public App()
        {
            InitializeComponent();

            initFFmpeg = InitFFmpeg.instance;
            KB_HOOK = new TaskPoolGlobalHook();
            MainPage = new AppShell();

            var CAPTURE_OPTIONS = Environment.GetEnvironmentVariable("OPENCV_FFMPEG_CAPTURE_OPTIONS");
            if (CAPTURE_OPTIONS == null)
            {
                //解决 rtsp 中断时，read 方法不返回， 导致线程阻塞的问题
                Environment.SetEnvironmentVariable("OPENCV_FFMPEG_CAPTURE_OPTIONS", "timeout;1000|fflags;nobuffer|flags;low_delay");

                //Environment.SetEnvironmentVariable("OPENCV_FFMPEG_CAPTURE_OPTIONS", "timeout;1000|hwaccel;cuvid|video_codec;h264_cuvid|vsync;0");
                Environment.SetEnvironmentVariable("OPENCV_FFMPEG_DEBUG", "true");
                Environment.SetEnvironmentVariable("OPENCV_FFMPEG_LOGLEVEL", "5");
            }
        }


        protected override async void OnStart()
        {
            base.OnStart();
            KB_HOOK.KeyPressed += KB_HOOK_KeyPressed;
            await KB_HOOK.RunAsync();
        }

        private async void KB_HOOK_KeyPressed(object sender, KeyboardHookEventArgs e)
        {
            if (e.Data.KeyCode == SharpHook.Native.KeyCode.VcEscape || e.Data.KeyCode == SharpHook.Native.KeyCode.VcExit)
            {
                Debug.WriteLine($"key pressed {e.Data.KeyCode} ");
                await MainThread.InvokeOnMainThreadAsync(() =>
                {
                    if (EscPage.ESC_PAGE_OPENED == 0)
                    {
                        var hwndNeedClose = Win32.GetActiveWindow();
                        OpenWindow(new Window(new EscPage(hwndNeedClose)));
                    }
                });
            }
            else if (e.Data.KeyCode == SharpHook.Native.KeyCode.VcF11)
            {
                Debug.WriteLine("F11 切换全屏");
                ChangeFullScreen();
            }
            else if (e.Data.KeyCode == SharpHook.Native.KeyCode.VcF10)
            {
                Debug.WriteLine("F10 新建摄像头");
                WeakReferenceMessenger.Default.Send(new AddCameraMsg(""), "AddCamera");
            }
        }

        private void ChangeFullScreen()
        {
            WeakReferenceMessenger.Default.Send(new ChangeFullScreenMsg(""), "ChangeFullScreen");
        }
    }
}